﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace RuoVea.ExUtil;

public static partial class Extensions
{
    #region Splice(拼接集合元素)

    /// <summary>
    /// 拼接集合元素
    /// </summary>
    /// <typeparam name="T">集合元素类型</typeparam>
    /// <param name="list">集合</param>
    /// <param name="quotes">引号，默认不带引号，范例：单引号 "'"</param>
    /// <param name="separator">分隔符，默认使用逗号分隔</param>
    /// <returns>string</returns>
    public static string Splice<T>(this IEnumerable<T> list, string quotes = "", string separator = ",")
    {
        if (list == null)
            return string.Empty;
        var result = new StringBuilder();
        foreach (var each in list)
            result.AppendFormat("{0}{1}{0}{2}", quotes, each, separator);
        return result.ToString().TrimEnd(separator.ToCharArray());
    }

    #endregion

    #region FirstUpper(将值的首字母大（小）写)

    /// <summary>
    /// 将值的首字母大写
    /// </summary>
    /// <param name="value">值</param>
    /// <returns>字符串</returns>
    public static string FirstUpper(this string value)
    {
        string firstChar = value.Substring(0, 1).ToUpper();
        return firstChar + value.Substring(1, value.Length - 1);
    }

    /// <summary>
    /// 将值的首字母小写
    /// </summary>
    /// <param name="value">值</param>
    /// <returns>字符串</returns>
    public static string FirstLower(this string value)
    {
        string firstChar = value.Substring(0, 1).ToLower();
        return firstChar + value.Substring(1, value.Length - 1);
    }
    #endregion

    #region ToCamel(将字符串转成驼峰形式)

    /// <summary>
    /// 将字符串转成驼峰形式
    /// </summary>
    /// <param name="value">原始字符串</param>
    /// <returns>字符串</returns>
    public static string ToCamel(this string value)
    {
        return FirstUpper(value.ToLower());
    }

    /// <summary>
    /// 将字符串转成驼峰形式 去除下划线
    /// </summary>
    /// <param name="value">原始字符串</param>
    /// <returns>字符串</returns>
    public static string ToCamelAny(this string value)
    {
        if (string.IsNullOrWhiteSpace(value))
            return string.Empty;

        string[] s = value.ToLower().Split("_");
        string strName = string.Empty;

        foreach (var c in s)
        {
            strName += FirstUpper(c.ToLower());
        }
        return strName;
    }

    #endregion

    #region ContainsChinese(是否包含中文)

    /// <summary>
    /// 是否包含中文
    /// </summary>
    /// <param name="text">文本</param>
    /// <returns>对应类型值</returns>
    public static bool ContainsChinese(this string text)
    {
        const string pattern = "[\u4e00-\u9fa5]+";
        return Regex.IsMatch(text, pattern);
    }

    #endregion

    #region ContainsNumber(是否包含数字)

    /// <summary>
    /// 是否包含数字
    /// </summary>
    /// <param name="text">文本</param>
    /// <returns>对应类型值</returns>
    public static bool ContainsNumber(this string text)
    {
        const string pattern = "[0-9]+";
        return Regex.IsMatch(text, pattern);
    }

    #endregion

    #region Distinct(去除重复)

    /// <summary>
    /// 去除重复
    /// </summary>
    /// <param name="value">值，范例1："5555",返回"5",范例2："4545",返回"45"</param>
    /// <returns>对应类型值</returns>
    public static string Distinct(this string value)
    {
        var array = value.ToCharArray();
        return new string(array.Distinct().ToArray());
    }

    #endregion

    #region Truncate(截断字符串)

    /// <summary>
    /// 截断字符串
    /// </summary>
    /// <param name="text">文本</param>
    /// <param name="length">返回长度</param>
    /// <param name="endCharCount">添加结束符号的个数，默认0，不添加</param>
    /// <param name="endChar">结束符号，默认为省略号</param>
    /// <returns>对应类型值</returns>
    public static string Truncate(this string text, int length, int endCharCount = 0, string endChar = ".")
    {
        if (string.IsNullOrWhiteSpace(text))
            return string.Empty;
        if (text.Length < length)
            return text;
        return text.Substring(0, length) + GetEndString(endCharCount, endChar);
    }

    /// <summary>
    /// 获取结束字符串
    /// </summary>
    /// <param name="endCharCount">总数</param>
    /// <param name="endChar">结束字符串</param>
    /// <returns>对应类型值</returns>
    private static string GetEndString(int endCharCount, string endChar)
    {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < endCharCount; i++)
            result.Append(endChar);
        return result.ToString();
    }

    #endregion

    #region GetLastProperty(获取最后一个属性)

    /// <summary>
    /// 获取最后一个属性
    /// </summary>
    /// <param name="propertyName">属性名，范例，A.B.C,返回"C"</param>
    /// <returns>string</returns>
    public static string GetLastProperty(this string propertyName)
    {
        if (propertyName.IsEmpty())
            return string.Empty;
        var lastIndex = propertyName.LastIndexOf(".", StringComparison.Ordinal) + 1;
        return propertyName.Substring(lastIndex);
    }

    #endregion

    #region  取得HTML中所有图片的 URL
    /// <summary>   
    /// 取得HTML中所有图片的 URL。   
    /// </summary>  
    /// <param name="sHtmlText">HTML代码</param>  
    /// <returns>图片的URL列表</returns>   
    public static string[] GetHtmlImageUrlList(this string sHtmlText)
    {
        // 定义正则表达式用来匹配 img 标签   
        Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
        // 搜索匹配的字符串   
        MatchCollection matches = regImg.Matches(sHtmlText);
        int i = 0;
        string[] sUrlList = new string[matches.Count];
        // 取得匹配项列表   
        foreach (Match match in matches)
            sUrlList[i++] = match.Groups["imgUrl"].Value;
        return sUrlList;
    }
    #endregion

    #region 过滤Emoji
    /// <summary>
    /// 过滤Emoji
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string FilterEmoji(this string str)
    {

        string origin = str;
        try
        {
            //关键代码
            foreach (var a in str)
            {
                byte[] bts = Encoding.UTF32.GetBytes(a.ToString());
                if (bts[0].ToString() == "253" && bts[1].ToString() == "255")
                {
                    str = str.Replace(a.ToString(), "");
                }
            }
        }
        catch (Exception)
        {
            str = origin;
        }
        return str;
    }
    #endregion

    #region 字符串转换Long类型
    /// <summary>
    /// 将字符串转换为long类型数组
    /// </summary>
    /// <param name="str">如1,2,3,4,5</param>
    /// <returns></returns>
    public static List<long> StrToListLong(this string str)
    {
        var list = new List<long>();
        if (!str.Contains(","))
        {
            list.Add(long.Parse(str));
            return list;
        }
        var slist = str.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        list.AddRange(slist.Select(long.Parse));
        return list;
    }
    #endregion

    /// <summary>
    /// 
    /// </summary>
    /// <param name="value"></param>
    /// <param name="pattern"></param>
    /// <param name="options"></param>
    /// <returns></returns>
    public static bool IsMatch(this string value, string pattern, RegexOptions options)
    {
        return value != null && Regex.IsMatch(value, pattern, options);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="value"></param>
    /// <param name="pattern"></param>
    /// <returns></returns>
    public static bool IsMatch(this string value, string pattern)
    {
        return value != null && Regex.IsMatch(value, pattern);
    }
    /// <summary>
    /// 分割时间，查询作用
    /// </summary>
    /// <param name="timeStr"></param>
    /// <param name="split"></param>
    /// <returns></returns>
    public static (string beginTime, string endTime) Splitting(this string timeStr, char split = '/')
    {
        var time = timeStr.Split(new char[] { split }, StringSplitOptions.RemoveEmptyEntries);
        return (time[0], time[1]);
    }
}
